// TCPSocketClient.cpp

#include "stdafx.h"
#include "TCPSocketClient.h"

const int ZERO = 0;

#define PER_FRAME_SIZE (640 * 480 * 4)

TCPSocketClient::TCPSocketClient(void)
    : m_socketTCP(0)
    , m_pParent(nullptr)
{
}

TCPSocketClient::~TCPSocketClient(void)
{
    if (m_pParent != nullptr)
    {
        delete m_pParent;
        m_pParent = nullptr;
    }
}

DWORD TCPSocketClient::OpenTCP(
    void* pParent,
    std::string strServerHost,
    int nServerPort)
{
    if (pParent == nullptr)
    {
        return -1;
    }
    m_pParent = pParent;

    WSADATA wsa;
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        return -2;
    }

    m_socketTCP = socket(AF_INET, SOCK_STREAM, 0);
    if (m_socketTCP == INVALID_SOCKET)
    {
        return -3;
    }

    m_sockaddrin.sin_family = AF_INET;
    m_sockaddrin.sin_port = htons(nServerPort);
    m_sockaddrin.sin_addr.S_un.S_addr = inet_addr(strServerHost.c_str());

    if (connect(m_socketTCP, (sockaddr*)&m_sockaddrin, sizeof(m_sockaddrin)) == SOCKET_ERROR)
    {
        return -4;
    }

    setsockopt(m_socketTCP, SOL_SOCKET, SO_SNDBUF, (char*)&ZERO, sizeof(ZERO));

    return 1;
}

DWORD TCPSocketClient::CloseTCP(void)
{
    if (closesocket(m_socketTCP) == SOCKET_ERROR)
    {
        return -1;
    }

    if (WSACleanup() == SOCKET_ERROR)
    {
        return -2;
    }

    return 1;
}

DWORD TCPSocketClient::SendData(std::string strBuffer)
{
    int nAlreadSendBytes = 0;
    int nErrorCode = 0;

    nAlreadSendBytes = send(m_socketTCP, strBuffer.c_str(), static_cast<int>(strBuffer.size()), 0);
    if (nAlreadSendBytes == SOCKET_ERROR)
    {
        nErrorCode = WSAGetLastError();

        if (m_pfOnTCPError != nullptr)
        {
            m_pfOnTCPError(m_pParent, nErrorCode);
        }

        return -1;
    }
    if (nAlreadSendBytes != strBuffer.size())
    {
        return -2;
    }

    return nAlreadSendBytes;
}
